﻿#include "sensorinputwidget.h"
#include "ui_sensorinputwidget.h"

SensorInputWidget::SensorInputWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SensorInputWidget),
    m_itemPerPage(16),
    m_pGetSenserTimer(NULL)
{
    ui->setupUi(this);

    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;
    m_sensorsTypeIdx = -1;

    m_pGetSenserTimer = new QTimer(this);
    connect(m_pGetSenserTimer, SIGNAL(timeout()),
            this, SLOT(slotOnRefTimer()));

    initData();
    initControl();
    refreshUi();
}

SensorInputWidget::~SensorInputWidget()
{
    delete m_pGetSenserTimer;
    delete ui;
}

void SensorInputWidget::initData()
{
    m_curPage = 0;                 // 当前页
    m_allSensorItemList.clear();
    m_sensorItemList.clear();
    m_itemList.clear();
    m_sensorsDat.clear();
}

//初始化窗体控件，包括位置、尺寸、样式
void SensorInputWidget::initControl()
{
    m_SensorBtnList.append(ui->button1);
    m_SensorBtnList.append(ui->button2);
    m_SensorBtnList.append(ui->button3);
    m_SensorBtnList.append(ui->button4);
    m_SensorBtnList.append(ui->button5);
    ui->button6->setVisible(true);//显示
    ui->button7->setVisible(true);
    ui->button8->setVisible(true);
    m_SensorBtnList.append(ui->button6);
    m_SensorBtnList.append(ui->button7);
    m_SensorBtnList.append(ui->button8);

    m_SensorBtnList.append(ui->button1_2);
    m_SensorBtnList.append(ui->button2_2);
    m_SensorBtnList.append(ui->button3_2);
    m_SensorBtnList.append(ui->button4_2);
    m_SensorBtnList.append(ui->button5_2);
    ui->button6_2->setVisible(true);
    ui->button7_2->setVisible(true);
    ui->button8_2->setVisible(true);
    m_SensorBtnList.append(ui->button6_2);
    m_SensorBtnList.append(ui->button7_2);
    m_SensorBtnList.append(ui->button8_2);

    //根据不同分辨率设置控件的位置和尺寸
    initResolution();
    initControlStyle();//初始化窗体控件样式
}

//初始化窗体控件为任意分辨率
void SensorInputWidget::initResolution()
{

    double factoryX = getFactoryX();
    double factoryY = getFactoryY();

    this->resize(GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->frameBack->setGeometry(0*factoryX,0*factoryY,GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->buttonTypeLogo->setGeometry(GLB_EDGE_WIGHT*factoryX,GLB_EDGE_HEIGHT*factoryY,GLB_LICON_SIZE*factoryX,GLB_LICON_SIZE*factoryY);
    ui->labelMainTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT)*factoryX,GLB_EDGE_HEIGHT*factoryY,
                                    (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT*2))*factoryX,GLB_TEXT_L_HEIGHT*factoryY);
    ui->labelSubTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT)*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_TEXT_HEIGHT)*factoryY,
                                   (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT*2))*factoryX,GLB_TEXT_HEIGHT*factoryY);

    int sensor_w = (GLB_PARA_WIGHT - GLB_BAS_WIGHT) / 2;    // 传感器宽度

    QRect rectName(GLB_TAB_WIGHT*factoryX,
                   (GLB_EDGE_WIGHT+(GLB_PARA_HEIGHT-GLB_TEXT_L_HEIGHT)/2)*factoryY,
                   GLB_TEXT_HEIGHT*factoryX,
                   GLB_TEXT_HEIGHT*factoryY);
    QRect rectValue((GLB_TAB_WIGHT+GLB_TEXT_HEIGHT)*factoryX,
                    (GLB_BAS_WIGHT+(GLB_PARA_HEIGHT-GLB_TEXT_HEIGHT)/2)*factoryY,
                    (sensor_w-GLB_TAB_WIGHT-GLB_TEXT_HEIGHT)*factoryX,
                    GLB_TEXT_HEIGHT*factoryY);
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < m_itemPerPage/2; j++)
        {
            m_SensorBtnList[i*(m_itemPerPage/2) + j]->setGeometry((GLB_PARA_LEFT+i*(sensor_w + GLB_BAS_WIGHT))*factoryX,
                                                                  (GLB_PARA_TOP + j * GLB_PARA_HEIGHT +3)*factoryY,
                                                                  sensor_w*factoryX,
                                                                  (GLB_PARA_HEIGHT-3)*factoryY);

            m_SensorBtnList[i*(m_itemPerPage/2) + j]->initLeftNameRightValue(rectName,rectValue);
        }
    }

    ui->framePageBtn->setGeometry(0*factoryX,(GLB_SCR_HEIGHT-GLB_LBUT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->labelPage->setGeometry(GLB_EDGE_WIGHT*factoryX,(GLB_SCR_HEIGHT-GLB_TEXT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,(GLB_SCR_WIGHT/3)*factoryX,GLB_TEXT_HEIGHT*factoryY);
    ui->buttonPgUp->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*2+GLB_LBUT_WIGHT*3))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgDn->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_LBUT_WIGHT*2))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonBack->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*0+GLB_LBUT_WIGHT*1))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
}

//初始化窗体控件样式
void SensorInputWidget::initControlStyle()
{
    SetStyle setControlStyle;
    setControlStyle.setUiName(this->objectName());

    //背景图
    QString frameBackImgPath = setControlStyle.getSharedStyleSheet();
    ui->frameBack->setStyleSheet(frameBackImgPath);
    ui->labelMainTitle->setFont(fontSize_L());
    ui->labelMainTitle->setStyleSheet(titleTextColour());
    ui->labelSubTitle->setFont(fontSize_M());
    ui->labelSubTitle->setStyleSheet(noteTextColour());
    ui->labelPage->setFont(fontSize_M());
    ui->labelPage->setStyleSheet(commonTextColour());

    for(int i = 0; i < m_SensorBtnList.size(); i++)
    {
        m_SensorBtnList[i]->setEnabled(false);
        m_SensorBtnList[i]->setLabelValueFont(fontSize_M());
        m_SensorBtnList[i]->setLabelNameFont(fontSize_L());
    }

    //四个按钮样式表一样
    ui->buttonPgUp->setStyleSheet(confirmIconStyle());
    ui->buttonPgUp->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgUp->objectName()),12);

    ui->buttonPgDn->setStyleSheet(confirmIconStyle());
    ui->buttonPgDn->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgDn->objectName()),12);

    ui->buttonBack->setStyleSheet(confirmIconStyle());
    ui->buttonBack->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonBack->objectName()),12);
}

//设置类型图标
void SensorInputWidget::setTypeLogo(QString tStyle)
{
    ui->buttonTypeLogo->setUnPreBtnLogo(tStyle);
}

void SensorInputWidget::setMainTitle(QString title)
{
    ui->labelMainTitle->setText(title);
}

//设置副title
void SensorInputWidget::setSubTitle(QString title)
{
    ui->labelSubTitle->setText(title);
}

int SensorInputWidget::addSensorItems(QList<SensorItem> itemList)
{
    m_allSensorItemList.append(itemList);
    return (m_allSensorItemList.size() - itemList.size());
}

void SensorInputWidget::setMachine(Machine *pMc)
{
    g_pMachine = pMc;
}

void SensorInputWidget::refreshUi()
{
//    QList<SensorItem> itemList;
//    itemList.clear();

#if(0)//测试用
    m_SensorBtnList[0]->setLabelValue("11111");
    m_SensorBtnList[0]->setLabelName("■");
#endif

    if(m_itemPerPage <= 0)
    {
        return;
    }

    if(m_sensorsTypeIdx == -1)//传感器信号不分类
    {
        m_itemList.clear();
        m_itemList.append(m_sensorItemList);//根据下位机位图过滤的传感器信号列表放在itemList里
    }
    else
    {
        getItemList(m_itemList); //根据不同主板加载的分类传感器信号
    }

    //-----------
    int itemNum, pageNums;
    itemNum = m_itemList.size();

    //qDebug()<< "RefreshUi m_sensorItemList = "<<itemNum;
    pageNums = (itemNum+m_itemPerPage-1) / m_itemPerPage;

    if (m_curPage > pageNums)                 // 当前页
    {
        m_curPage = pageNums;
    }
    if (m_curPage <= 1)
    {
        m_curPage = 1;
    }

    // 刷新文本
    int i, itemidx;
    itemidx = (m_curPage-1) * m_itemPerPage;
    for (i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            if(m_itemList[itemidx].m_name.length() <= 0)//字符长度为空
            {
               //QString str = "byte:" + QString::number(itemList[itemidx].m_byte_offset) + "  bit:" + QString::number(m_sensorItemList[itemidx].m_bit_offset);
                QString str = "byte:" + QString::number(m_itemList[itemidx].m_byte_offset,16).toUpper() + "  bit:" + QString::number(m_itemList[itemidx].m_bit_offset);
                qDebug()<<"字符长度为空"<<str;
                m_SensorBtnList.at(i)->setLabelValue(str);
            }
            else
            {
                m_SensorBtnList.at(i)->setLabelValue(m_itemList.at(itemidx).m_name);
            }
            m_SensorBtnList.at(i)->show();
        }
        else
        {
            m_SensorBtnList.at(i)->hide();
        }
        itemidx++;
    }

    // 刷新信号
    refreshSensors();

    // 刷新按钮
    if (m_curPage <= 1)
    {
        ui->buttonPgUp->setEnabled(false);
    }
    else
    {
        ui->buttonPgUp->setEnabled(true);
    }
    if (m_curPage >= pageNums)
    {
        ui->buttonPgDn->setEnabled(false);
    }
    else
    {
        ui->buttonPgDn->setEnabled(true);
    }

    if(pageNums == 0)
    {
        m_curPage = 0;
    }

    // 页信息
    QString str = tr("pageNum: ") + QString("%1/%2").arg(m_curPage).arg(pageNums);//页数:
    ui->labelPage->setText(str);
}

void SensorInputWidget::refreshSensors()
{
    QTextCodec *cod = QTextCodec::codecForLocale();
    if(m_sensorsDat.size() <= 0)
    {
        return;
    }

    //--------------------------
    int itemNum, pageNums;
//    itemNum = m_sensorItemList.size();//m_sensorItemList
    itemNum = m_itemList.size();
    pageNums = (itemNum+m_itemPerPage-1) / m_itemPerPage;

    if (m_curPage > pageNums)                 // 当前页
    {
        m_curPage = pageNums;
    }
    if (m_curPage <= 1)
    {
        m_curPage = 1;
    }

    // 刷新文本
    int i, itemidx;
    itemidx = (m_curPage-1) * m_itemPerPage;
    for (i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            //const SensorItem & item = m_sensorItemList.at(itemidx);//m_sensorItemList
            const SensorItem & item = m_itemList.at(itemidx);

            int bytepos = item.m_byte_offset;
            int bitinbyte = item.m_bit_offset;

            if (    bytepos >= 0 &&
                    bitinbyte >= 0 &&
                    bytepos < m_sensorsDat.size())
            {
                u8 curbyte = m_sensorsDat.at(bytepos);
                u8 mod = 0x01 << bitinbyte;

                if ((curbyte & mod) != 0)
                {
                    m_SensorBtnList.at(i)->setLabelName(cod->toUnicode("■"));
                    m_SensorBtnList.at(i)->setLabelNameStyle(ledTextColour());
                }
                else
                {
                    m_SensorBtnList.at(i)->setLabelName(cod->toUnicode("□"));
                    m_SensorBtnList.at(i)->setLabelNameStyle(commonTextColour());
                }
            }
            else
            {
                m_SensorBtnList.at(i)->setText("");
            }
        }
        else
        {
            break;
        }
        itemidx++;
    }
}

void SensorInputWidget::getItemList(QList<SensorItem> &ItemList)
{
    ItemList.clear();

    for(int i = 0; i < m_sensorItemList.size(); i++)
    {
        int type = m_sensorItemList[i].m_type;

        if((type & m_sensorsTypeIdx) != 0 && (type != -1))
        {
            ItemList.append(m_sensorItemList[i]);//筛选好的传感器信号，分类传感器信号
        }
    }
}

void SensorInputWidget::show()
{
    m_sensorsDat.clear();

    if (g_pMachine != NULL)
    { //如果没有传感器信号位图
        if (g_pMachine->isSensorBmpEn() == 0)
        {
            m_sensorItemList.clear();
            g_pMachine->getSensorEnBmpFromMachine();//读取传感器有效位图
            refreshUi();

            qDebug("send GetSensorEnBmpFromMachine");
        }
    }

    //emit(siEntrySensorScan());
    if (m_pGetSenserTimer != NULL)
    {
        m_pGetSenserTimer->start(500);//读取传感器信号
    }

    if (g_pMachine != NULL)
    {
        g_pMachine->entrySensorScan();
    }

    qDebug("SensorInputWidget::show");

    QWidget::show();
}

void SensorInputWidget::hide()
{
    if (m_pGetSenserTimer != NULL)
    {
        m_pGetSenserTimer->stop();
    }

    //emit(siExitSensorScan());

    if (g_pMachine != NULL)
    {
        g_pMachine->exitSensorScan();
    }

    qDebug("SensorInputWidget::hide");

    QWidget::hide();
}

void SensorInputWidget::slotRefSensorBitmap(SensorsBitmap map)
{
    qDebug("SlotRefSensorBitmap");
    m_sensorItemList.clear();

    if (g_pMachine != NULL)
    {
        if (g_pMachine->isSensorBmpEn() != 0)
        {
            QByteArray sensorsbmp;
            sensorsbmp.resize(sizeof(SensorsBitmap));
            memcpy(sensorsbmp.data(), &map, sizeof(SensorsBitmap));

            int ssize = m_allSensorItemList.size() ;//m_allSensorItemList 8192个  机型里的所有主板的传感器信号
            int fsize = sensorsbmp.size();
            int size = (ssize < fsize) ? ssize:fsize;
            for (int i = 0; i < size; i++)
            {
                unsigned char fdat = sensorsbmp.at(i);
                for (int j = 0; j < 8; j++)
                {
                    const SensorItem & item = m_allSensorItemList.at( i*8 + j);
                    if ((fdat & 0x01) != 0)
                    {
                        m_sensorItemList.append(item);//根据下位机过滤好的传感器列表
                    }
                    fdat >>= 1 ;
                }
            }

            qDebug("m_sensorItemList.size=%d", m_sensorItemList.size());
            refreshUi();
        }
    }
}
//接收传感器状态改变的槽函数
void SensorInputWidget::slotRefSensorsDat(SensorsBitmap dat)
{
    // 读取信号
    m_sensorsDat.clear();
    m_sensorsDat.resize(sizeof(SensorsBitmap));
    memcpy(m_sensorsDat.data(),&dat,sizeof(SensorsBitmap));

    // 更新视图
    refreshSensors();
}

void SensorInputWidget::slotOnRefTimer()
{
    if (g_pMachine != NULL)
    {
        g_pMachine->getSensorsFromMachine();        // 读取一次信号
    }
}

void SensorInputWidget::on_buttonPgUp_clicked()
{
    m_curPage--;
    refreshUi();
}

void SensorInputWidget::on_buttonPgDn_clicked()
{
    m_curPage++;
    refreshUi();
}

void SensorInputWidget::on_buttonBack_clicked()
{
    this->hide();
}

void SensorInputWidget::mousePressEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mousePressX = e->x();
        m_mousePressY = e->y();
        m_mouseReleaseX = 0;
        m_mouseReleaseY = 0;
    }
}

void SensorInputWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mouseReleaseX = e->x();
        m_mouseReleaseY = e->y();
    }

    int width = this->width();
    int height = this->height();
    if ((m_mousePressX >= 0 && m_mousePressX <= 100)  &&
            ((m_mousePressY >= (height - 100)) && m_mousePressY <= height) &&
            ((m_mouseReleaseX >= (width - 100)) && m_mouseReleaseX <= width) &&
            ((m_mouseReleaseY >= (height - 100)) && m_mouseReleaseY <= height))
    {
        MainWidgetFunction mainFunction;
        QString usbPath;//优盘路径
        usbPath = mainFunction.detectUsb();//优盘检测
        if(usbPath.length() <= 0)
        {
            //优盘不存在
            return;
        }
        else
        {
            QPixmap pixmap=QPixmap::grabWindow(this->winId(),0,0,this->width(),this->height());//截屏存放在pixmap
            QString name_pc = usbPath +  "EMB" + //
                    QDateTime::currentDateTime().toString("yyyyMMdd") +//获取时期时间
                    +"_"+
                    QDateTime::currentDateTime().toString("hhmmss")    + ".png";

            pixmap.save(name_pc,"png"); // 路径
        }
    }

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;
}
